/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FasesView.java
 *
 * Created on 05/11/2011, 14:09:36
 */
package praticav.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;
import org.hibernate.HibernateException;
import org.hibernate.exception.ConstraintViolationException;
import praticav.dao.FasesDAO;
import praticav.dao.ProducaoDAO;
import praticav.model.Fases;
import praticav.model.FasesPK;
import praticav.model.Producao;

/**
 *
 * @author Katiane
 */
public class FasesView extends javax.swing.JFrame {
    int conta;
    int cod;
    int codPro=0;
    int predecessor;
    int sequencial;
    String desc;
    Date dInicial;
    Date dFinal;
    
    /** Creates new form FasesView */
    public FasesView(int codigoPro) {
        initComponents();
        conta = 0;
        codPro = codigoPro;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtDescricaoFase = new javax.swing.JTextField();
        lblCodigoProducao = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        txtPredecessor = new javax.swing.JTextField();
        btnSalvar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Descrição da Fase"));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtDescricaoFase, javax.swing.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(txtDescricaoFase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        lblCodigoProducao.setFont(new java.awt.Font("Arial", 1, 18));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Predecessor"));

        txtPredecessor.setText("0");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtPredecessor, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(70, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(txtPredecessor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/praticav/images/save.png"))); // NOI18N
        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/praticav/images/close.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 191, Short.MAX_VALUE)
                        .addComponent(btnCancelar))
                    .addComponent(lblCodigoProducao, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblCodigoProducao, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnSalvar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    /*
    public FasesView(int codigo, int codigoPro, String descricao, Date datainicial, Date datafinal) {
        try {
            cod = codigo;
            codPro = codigoPro;
            desc = descricao;
            dInicial = datainicial;
            dFinal = datafinal;
            conta=1;
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        initComponents();        
        txtDescricaoFase.setText(""+descricao);
        //txtDtaInicialFormatada.setText(""+datainicial);
        //txtDtaFinalFormatada.setText(""+datafinal);
    }
    */
    public FasesView(Fases f) {
        try {
            cod = f.getChave().getFascodigo();
            codPro = f.getChave().getProducao().getProcodigo();
            desc = f.getFasdescricao();
            dInicial = f.getFasdtainicial();
            dFinal = f.getFasdtainicial();
            predecessor = f.getFaspredecessor();
            sequencial = f.getFassequencial();
            conta=1;
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        initComponents();        
        txtDescricaoFase.setText(""+f.getFasdescricao());
        txtPredecessor.setText(""+f.getFaspredecessor());
    }
    
    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        // Salvar
        if (txtDescricaoFase.getText().equals("") || txtPredecessor.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Todos os CAMPOS devem estar preenchidos!", "Atenção", WIDTH);
        } else {
            if (conta==0) {
                Fases f = new Fases();
                f.setFasdescricao(txtDescricaoFase.getText());
                Producao p = new Producao();
                p.setProcodigo(codPro);
                FasesPK chave = new FasesPK();
                chave.setProducao(p);
                f.setChave(chave);
                
                try {
                    f.setFasdtainicial(new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2011"));
                } catch (ParseException e) {
                    JOptionPane.showMessageDialog(null, "Data incorreta!");
                }
                try {
                    f.setFasdtafinal(new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2011"));
                } catch (ParseException e) {
                    JOptionPane.showMessageDialog(null, "Data incorreta!");
                }
                
                FasesDAO dao = new FasesDAO();
                
                try{
                    dao.inserir(f);
                } catch(ConstraintViolationException ce){
                    JOptionPane.showMessageDialog(null, "Erro ao gravar os dados!!!  "+ ce.getMessage());
                } catch (HibernateException ex){
                    JOptionPane.showMessageDialog(null, "Erro: "+ex.getMessage());
                }
                
                txtDescricaoFase.setText("");
                txtPredecessor.setText("");
                this.hide();
            } else {
                Fases f = new Fases();
                FasesPK chave = new FasesPK();
                chave.setFascodigo(cod);
                chave.setProducao(new ProducaoDAO().buscar(codPro));
                f.setChave(chave);
                f.setFasdescricao(txtDescricaoFase.getText());
                f.setFassequencial(sequencial);
                f.setFaspredecessor(Integer.parseInt(txtPredecessor.getText()));
                
                SimpleDateFormat formatarDate = new SimpleDateFormat("dd/MM/yyyy");   
                String DataStrIni = formatarDate.format(dInicial.getTime());
                
                //SimpleDateFormat formatarDate = new SimpleDateFormat("dd/MM/yyyy");   
                String DataStrFim = formatarDate.format(dFinal.getTime());
                
                try {
                    f.setFasdtainicial(new SimpleDateFormat("dd/MM/yyyy").parse(DataStrIni));
                } catch (ParseException e) {
                    JOptionPane.showMessageDialog(null, "Data incorreta!");
                }
                try {
                    f.setFasdtafinal(new SimpleDateFormat("dd/MM/yyyy").parse(DataStrFim));
                } catch (ParseException e) {
                    JOptionPane.showMessageDialog(null, "Data incorreta!");
                }
                
                FasesDAO dao = new FasesDAO();
                
                try{
                    dao.editar(f);
                } catch(ConstraintViolationException ce){
                    JOptionPane.showMessageDialog(null, "Erro ao gravar os dados!!!  "+ ce.getMessage());
                } catch (HibernateException ex){
                    JOptionPane.showMessageDialog(null, "Erro: "+ex.getMessage());
                }
                
                txtDescricaoFase.setText("");
                txtPredecessor.setText("");
                this.hide();
            }
        }
}//GEN-LAST:event_btnSalvarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // Cancelar
        this.hide();
}//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        lblCodigoProducao.setText("Produção "+codPro);
        
        if (conta == 0)
        {
            this.setTitle("Cadastro de Fases da Produção");
        }else
        {
            this.setTitle("Alteração de Fases da Produção");
        }
        /*
        MaskFormatter formater = new MaskFormatter(); 
        
        try {
            formater.setMask("##/##/####");
        } catch (ParseException ex) {
            Logger.getLogger(FasesView.class.getName()).log(Level.SEVERE, null, ex);
        }
        formater.install(txtDtaInicialFormatada);
         * 
         */
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel lblCodigoProducao;
    private javax.swing.JTextField txtDescricaoFase;
    private javax.swing.JTextField txtPredecessor;
    // End of variables declaration//GEN-END:variables

}
